//
//  JobHomeViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/8/15.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "JobHomeViewController.h"
#import "JobRecommendListViewController.h"
#import <XRCarouselView.h>
#import "CCZSegementController.h"
#import "AdsServer.h"
#import <CoreLocation/CoreLocation.h>
#import "UIButton+zt_adjustImageAndTitle.h"
#import "JFCityViewController.h"

@interface JobHomeViewController ()<UIScrollViewDelegate, UISearchBarDelegate, CLLocationManagerDelegate, JFCityViewControllerDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) JobRecommendListViewController *recommendListVC;
@property (strong, nonatomic) XRCarouselView *carouselView;
@property (strong, nonatomic) CCZSegementController *reccomendInfoSegment;
@property (strong ,nonatomic) UIView *topView;
@property (strong ,nonatomic) UILabel *jobType;
@property (strong ,nonatomic) UILabel *distance;
@property (strong ,nonatomic) UIButton *returnBtn;
@property (strong ,nonatomic) CLLocationManager *locationManager;
@property (strong ,nonatomic) CLGeocoder *geocoder;

@property (strong ,nonatomic) NSMutableArray *categoryIdArr;
@property (strong ,nonatomic) NSMutableArray *categoryNameArr;

@end

@implementation JobHomeViewController

- (void)viewWillAppear:(BOOL)animated {
	[self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
	[self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	
	//获取通知中心
	NSNotificationCenter * center =[NSNotificationCenter defaultCenter];
	[center addObserver:self selector:@selector(endJobRefresh:) name:@"endJobRefresh" object:nil];
	[center addObserver:self selector:@selector(returnTop:) name:@"returnTop" object:nil];
	[center addObserver:self selector:@selector(refreshUI:) name:@"changePostJob" object:nil];
	
	[self buildUI];
	[self GETAds];
	[self.locationManager startUpdatingLocation];
	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)buildUI
{
	self.view.backgroundColor = kWhiteColor;
	UIView *headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, Height_NavBar)];
	[self.view addSubview:headBgView];
	headBgView.backgroundColor = UIMainColorRGB;
	
	// 定位btn
	UIButton *locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	locationBtn.tag = 1;
	
	if (IS_IPHONE_X || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) {
		locationBtn.frame = CGRectMake(10, headBgView.height/2-10, 90, 44);
	}
	else {
		locationBtn.frame = CGRectMake(10, headBgView.height/2-15, 90, 44);
	}
	[headBgView addSubview:locationBtn];
	[locationBtn setTitle:@"定位中" forState:UIControlStateNormal];
	[locationBtn setImage:IMAGE(@"job_nav_position") forState:UIControlStateNormal];
	locationBtn.zt_contentAdjustType = ZTContentAdjustImageLeftTitleRight;
	[locationBtn zt_beginAdjustContent];
	[locationBtn addTarget:self action:@selector(locationBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	
	
	UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 0, SCREEN_WIDTH-130, 30)];
	[headBgView addSubview:searchBar];
	searchBar.centerY = locationBtn.centerY;
	searchBar.placeholder = @"请输入要查询的岗位/人才信息…";
	searchBar.backgroundImage = IMAGE(@"clearImage");
	searchBar.layer.cornerRadius = searchBar.height/2;
	searchBar.layer.masksToBounds = YES;
	searchBar.keyboardType = UIKeyboardTypeDefault;
	searchBar.delegate = self;
	searchBar.searchBarStyle = UISearchBarStyleDefault;
	UIView *searchTextField = [searchBar valueForKey:@"_searchField"];
	searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
	
	[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:kWhiteColor];
	[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:@"取消"];
	
	_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, headBgView.height, SCREEN_WIDTH, SCREEN_HEIGHT)];
	_scrollView.delegate = self;
    _scrollView.backgroundColor = kWhiteColor;
	[self.view addSubview:_scrollView];
	_scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
		NSLog(@"招聘首页下拉刷新选中下标的list");
		JobRecommendListViewController *jobListVC =  self.reccomendInfoSegment.viewControllers[self.reccomendInfoSegment.selectedNavAtIndex];
		jobListVC.page = 1;
		[jobListVC getJobInfo];
	}];
	
	_topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(2))];
	[self.scrollView addSubview:_topView];
	_carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(2))];
	_carouselView.contentMode = UIViewContentModeScaleAspectFill;
	_carouselView.imageArray = @[IMAGE(@"img.jpg")];
	_carouselView.time = 2;
	[_topView addSubview:_carouselView];
	[self.topView addSubview:_carouselView];
	
	[self getRecommendJobCategory];
	
	_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT+_topView.height);
	
}

- (void)segReturnClick:(UIButton *)sender {
	sender.hidden = YES;
	_scrollView.delegate = nil;
	_scrollView.scrollEnabled = YES;
	CGPoint offect = _scrollView.contentOffset;
	offect.y = - _scrollView.contentInset.top;
	[_scrollView setContentOffset:offect animated:NO];
	_scrollView.delegate = self;
    self.recommendListVC.jobListTableView.scrollEnabled = NO;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	
	if (scrollView.contentOffset.y > self.topView.height) {
		scrollView.scrollEnabled = YES;
		//scrollView.delegate = nil;
		[scrollView setContentOffset:CGPointMake(0, self.topView.height) animated:NO];
		for (JobRecommendListViewController *jobListVC in self.reccomendInfoSegment.viewControllers){
			jobListVC.jobListTableView.scrollEnabled = YES;
		}
	}
	else
	{
		for (JobRecommendListViewController *jobListVC in self.reccomendInfoSegment.viewControllers){
			jobListVC.jobListTableView.scrollEnabled = NO;
		}
	}
	
}


- (void)GETAds {
	[AdsServer GETAds:@{@"board":@"app_work_top"} xrView:_carouselView];
}

//职位搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	//NSInteger selectedIndex = self.reccomendInfoSegment.selectedNavAtIndex;
	for (JobRecommendListViewController *jobListVC in self.reccomendInfoSegment.viewControllers){
		jobListVC.keyword = searchBar.text;
	}
    [searchBar resignFirstResponder];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
	return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
	NSLog(@"开始输入搜索内容");
	
	// 取消字体颜色？
	searchBar.showsCancelButton = YES;
	[searchBar setShowsCancelButton:YES animated:YES];
    UITextField *searchBarTextField = nil;
    NSArray *views = ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) ? searchBar.subviews : [[searchBar.subviews objectAtIndex:0] subviews];
    for (UIView *subview in views)
    {
        if ([subview isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)subview;
            break;
            
        }
    }
    searchBarTextField.enablesReturnKeyAutomatically = NO;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
	NSLog(@"输入搜索完毕");
	
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
    self.recommendListVC.keyword = searchBar.text;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
	NSLog(@"取消搜索");
	
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
}

- (void)locationBtnClick:(UIButton *)sender
{
    /*
	if([CLLocationManager locationServicesEnabled])
	{
		NSLog(@"I am here 123125346465576");
		[self.locationManager requestWhenInUseAuthorization];
		[self.locationManager startUpdatingLocation];
	}
	else {
		[self presentViewController:[LZCTools alertMessage:@"无法定位，请检查是否已为本应用开启定位权限"] animated:YES completion:nil];
	}
     */
    JFCityViewController *cityVC = [[JFCityViewController alloc] init];
    cityVC.delegate = self;
    [self presentViewController:cityVC animated:YES completion:nil];
}

- (void)cityName:(NSString *)name {
    UIButton *locationBtn = [self.view viewWithTag:1];
    [locationBtn setTitle:name forState:UIControlStateNormal];
	
	//NSInteger selectedIndex = self.reccomendInfoSegment.selectedNavAtIndex;
	for (JobRecommendListViewController *jobListVC in self.reccomendInfoSegment.viewControllers){
		jobListVC.district = name;
	}
}

- (CLLocationManager *)locationManager
{
	if (!_locationManager) {
		_locationManager = [[CLLocationManager alloc] init];
		_locationManager.delegate = self;
		_locationManager.distanceFilter = kCLDistanceFilterNone;
		_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
		if([CLLocationManager locationServicesEnabled])
		{
			NSLog(@"I am here 123125346465576");
			[_locationManager requestWhenInUseAuthorization];
			[_locationManager startUpdatingLocation];
		}
		else {
			[self presentViewController:[LZCTools alertMessage:@"无法定位，请检查是否已为本应用开启定位权限"] animated:YES completion:nil];
		}
	}
	return _locationManager;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
	CLLocation *loc = [locations firstObject];
	
	//维度：loc.coordinate.latitude
	//经度：loc.coordinate.longitude
	NSLog(@"纬度=%f，经度=%f",loc.coordinate.latitude,loc.coordinate.longitude);
	[self.geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
		if (placemarks.count > 0){
			CLPlacemark *placemark = [placemarks objectAtIndex:0];
			//获取当前城市
			NSString *city = placemark.locality;
            NSString *area = placemark.subLocality;
            NSLog(@"%@%@", city,area);
			if (!city) {
				//注意：四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
				city = placemark.administrativeArea;
			}
			//NSArray *array = [city componentsSeparatedByString:@"市"];
			//NSString *cityStr = array[0];
			NSString *cityStr = city;
			UIButton *locationBtn = [self.view viewWithTag:1];
			[locationBtn setTitle:cityStr forState:UIControlStateNormal];
			for (JobRecommendListViewController *jobListVC in self.reccomendInfoSegment.viewControllers){
				jobListVC.district = cityStr;
			}
		}
		else if (error == nil && [placemarks count] == 0) {
			NSLog(@"没有结果返回.");
		}
		else if (error != nil)  {
			NSLog(@"An error occurred = %@", error);
		}
	}];
	[manager stopUpdatingLocation];
	
}

- (CLGeocoder *)geocoder
{
	if (!_geocoder) {
		_geocoder = [[CLGeocoder alloc] init];
	}
	return _geocoder;
}

- (NSMutableArray *)categoryIdArr
{
	if (!_categoryIdArr) {
		_categoryIdArr = [[NSMutableArray alloc] init];
	}
	return _categoryIdArr;
}

- (NSMutableArray *)categoryNameArr {
	if (!_categoryNameArr) {
		_categoryNameArr = [[NSMutableArray alloc] init];
	}
	return _categoryNameArr;
}

- (void) getRecommendJobCategory {
	[[NetworkTool sharedTool] requestWithName:@"获取推荐职位分类栏目" URLString:APIRecommendJobCategory parameters:nil method:@"GET" callBack:^(id responseObject) {
		NSArray *arr = responseObject[@"data"];
		[self.categoryIdArr removeAllObjects];
		[self.categoryNameArr removeAllObjects];
		for (NSDictionary *dict in arr){
			[self.categoryNameArr addObject:dict[@"category_title"]];
			[self.categoryIdArr addObject:dict[@"category_id"]];
		}
		[self createSegment];
	}];
}

- (void)createSegment {
	NSString *role = GetUserDefaule(USERINFO)[@"role"];
	NSMutableArray *segmentTitles = [[NSMutableArray alloc] init];
	NSMutableArray *vcArr = [[NSMutableArray alloc] init];
	JobRecommendListViewController *vc1 = [[JobRecommendListViewController alloc] init];
	JobRecommendListViewController *vc2 = [[JobRecommendListViewController alloc] init];
	vc2.category_id = @"-1";
	
	vc1.jobListTableView.scrollEnabled = NO;
	vc2.jobListTableView.scrollEnabled = NO;
	[vcArr addObject:vc1];
	[vcArr addObject:vc2];
	
	if ([role isEqualToString:@"5"] || [role isEqualToString:@"6"]) {
		[segmentTitles addObject:@"推荐人才"];
		[segmentTitles addObject:@"所有人才"];
		for (NSString *caterogyId in self.categoryIdArr){
			JobRecommendListViewController *vc = [[JobRecommendListViewController alloc] init];
			vc.category_id = caterogyId;
			vc.jobListTableView.scrollEnabled = NO;
			[vcArr addObject:vc];
		}
		for (NSString *categoryName in self.categoryNameArr) {
			[segmentTitles addObject:categoryName];
		}
	}
	else {
		[segmentTitles addObject:@"推荐岗位"];
		[segmentTitles addObject:@"所有岗位"];
	}
	
	_reccomendInfoSegment = [CCZSegementController segementControllerWithFrame:CGRectMake(0, _topView.y+_topView.height, SCREEN_WIDTH, SCREEN_HEIGHT-114) titles:segmentTitles];
	[_reccomendInfoSegment setSegementViewControllers:vcArr];
	_reccomendInfoSegment.style = CCZSegementStyleDefault;
	[_reccomendInfoSegment setSegementTintColor:UIMainColorRGB];
	//[_reccomendInfoSegment setContainViewOffSetX:0 Y:50];
	[self.scrollView addSubview:_reccomendInfoSegment.view];
	[self addChildViewController:_reccomendInfoSegment];
	[_reccomendInfoSegment selectedNavAtIndex:^(NSInteger index) {
		NSLog(@"招聘首页 index %ld",index);
	}];
	
	//参考首页的返回顶部按钮，不过暂时是隐藏的，往下滑也不显示出来
	_returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[_scrollView addSubview:_returnBtn];
	[_returnBtn setImage:IMAGE(@"icon_return_bg") forState:UIControlStateNormal];
	_returnBtn.titleLabel.text = @"222";
	_returnBtn.hidden = YES;
	[_returnBtn addTarget:self action:@selector(segReturnClick:) forControlEvents:UIControlEventTouchUpInside];
	_returnBtn.frame = CGRectMake(5, _reccomendInfoSegment.view.frame.origin.y+13, 20, 20);
}

- (void)refreshUI:(NSNotification *)notification{
	NSLog(@"切换角色刷新UI!!");
	[self.view removeAllSubViews];
	[self buildUI];
	[self GETAds];
}

- (void)endJobRefresh:(NSNotification *)notification{
	NSLog(@"刷新完毕");
	[self.scrollView.mj_header endRefreshing];
}

- (void)returnTop:(NSNotification *)notification{
	NSLog(@"回到顶部");
	[self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
